<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Tools\SendMessage;
use App\Models\Message;
use App\Models\User;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;



class MessagesController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('站内信列表');
            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header('编辑站内信');
            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('创建站内信');
            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Message::class, function (Grid $grid) {
            // 使用 with 来预加载商品类目数据，减少 SQL 查询
            $grid->model()->with(['user']);
            //dump($grid);exit;

//            $grid->filter(function($filter){
//
//                // 去掉默认的id过滤器
//                $filter->disableIdFilter();
//
//                // 在这里添加字段过滤器
//                $filter->like('title', '商品名称');
//                $filter->like('category.name', '类目');
//
//                $filter->equal('on_sale')->radio([
//                    ''   => 'All',
//                    0    => '未上架',
//                    1    => '已上架',
//                ]);
//
//
//            });

            //$grid->id('ID')->sortable();
            $grid->type('类型');
            $grid->notifiable_type('通知类型');
            $grid->column('user.name','接收者');

            $grid->read_at('是否已读')->display(function($read_at){
                if(empty($read_at)){
                    return '否';
                }else{
                    return $read_at;
                }
            });
            $grid->disableExport();
            $grid->actions(function ($actions) {
                $actions->disableView();
                $actions->prepend("<a href='/admin/messages/user/".$actions->getKey()."'><i class=\"fa fa-paper-plane\"></i></a>");
            });
            $grid->tools(function ($tools) {
                // 禁用批量删除按钮
                $tools->batch(function ($batch) {
                    $batch->disableDelete();

                });
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        // 创建一个表单
        return Admin::form(Message::class, function (Form $form) {
            // 创建一个输入框，第一个参数 title 是模型的字段名，第二个参数是该字段描述
            $form->text('type', '类型')->rules('required');
            $form->text('notifiable_type', '消息类型')->rules('required');
            // 添加一个类目字段，与之前类目管理类似，使用 Ajax 的方式来搜索添加
            $form->select('notifiable_id', '接收者')->options(function ($id) {
                $user = User::find($id);
                if ($user) {
                    return [$user->id => $user->name];
                }else{
                    return [0=>'所有人'];
                }
            })->ajax('/admin/api/users');
            // 创建一个富文本编辑器
            $form->editor('data', '消息')->rules('required');// 定义事件回调，当模型即将保存时会触发这个回调

        });
    }

    public function user(Content $content,$id)
    {
        return $content
            ->header('用户列表')
            ->body($this->usergrid($id));
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function usergrid($id)
    {


        $grid = new Grid(new User);
        $grid->id('Id');
        $grid->name('名称');
        $grid->img('头像')->image(env('APP_URL')."/storage",50,50);
        $grid->phone('手机号');
        $grid->iden('身份证号');
        $grid->grade('等级');
        $grid->recharge('充值金额');
        $grid->reward('奖励金额');
        $grid->distribution_invite_code('分佣邀请码');
        $grid->commission_invite_code('分销邀请码');
        $grid->status('状态');
        //$grid->remember_token('Remember token');
        $grid->created_at('创建时间');
        $grid->updated_at('修改时间');
        $grid->disableExport();
        //禁用批量删除按钮
        $grid->tools(function ($tools) {
            $tools->batch(function ($batch) {
                $batch->disableDelete();
            });
        });
        $grid->disableCreateButton();
        $grid->disableFilter();
        $grid->disableActions();
        $grid->tools(function ($tools)  use ($id) {
            // 禁用批量删除按钮
            $tools->batch(function ($batch)  use ($id) {
                $batch->disableDelete();
                $batch->add('发送站内信', new SendMessage($id));
            });
        });

        return $grid;
    }

    public function updatemessage(Request $request){
        $ids = $request->get('ids');
        $message_id = $request->get('message_id');
        $message_data = Message::find($message_id);
        $data = [];
         foreach($ids as $v){
            $data[] = [
              'type'=>$message_data['type'],
              'notifiable_type' => $message_data['notifiable_type'],
                'notifiable_id' => $v,
                'data' => $message_data['data'],
            ];
         }
        DB::table('notifications')->insert($data);
        return redirect('/');

    }

}
